<!doctype html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link href="../css/mui.picker.css" rel="stylesheet" />
		<link href="../css/mui.poppicker.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="../css/ReportMatter.css" />
		<link rel="stylesheet" type="text/css" href="css/app.css" />

		<script type="text/javascript">
			// 获取HTML的DOM
			var htmlDom = document.getElementsByTagName('html')[0];
			var htmlWidth = document.documentElement.clientWidth || document.body.clientWidth;
			// 设置html的fontsize
			htmlDom.style.fontSize = htmlWidth / 10 + 'px';
		</script>
		<style type="text/css">
			html,
			body {
				position: relative;
				height: 100%;
			}
		</style>
	</head>

	<body>
		<div id="matter">
			<header class="mui-bar mui-bar-nav">
				<h1 class="mui-title" style="color: #fff;">我要报修</h1>
			</header>
			<div class="content">
				<div class="list">
					<div class="item" @click="addressClick">
						<div class="item-icon">
							<img src="../images/address.png" />
						</div>
						<div class="item-title bottom-underline left-arrows">
							<span class="title">请选择地址</span>
							<span class="desc" id='addresstxt'></span>
						</div>
					</div>
					<div class="item" @click="classifyClick">
						<div class="item-icon">
							<img src="../images/classify.png" />
						</div>
						<div class="item-title left-arrows">
							<span class="title">请选择报修类型</span>
							<span class="desc" id='type'></span>
						</div>
					</div>
				</div>
				<div class="mui-input-row padding15">
					<textarea id="textarea" rows="5" placeholder="请说明您遇到的问题…"></textarea>
				</div>
				<form class="mui-input-group">
					<div class="mui-input-row">
						<label>联系人：</label>
						<input type="text" id='contactName' class="mui-input-clear" placeholder="请输入联系人">
					</div>
					<div class="mui-input-row">
						<label>联系人电话：</label>
						<input type="text" id='contactPhone' class="mui-input-clear" placeholder="请输入联系人电话">
					</div>
				</form>
				
				
				
				<div class="img-wapper padding15 bottom-underline">
					<div class="preview" v-for="(item,index) in listImg" v-if="listImg.length > 0">
						<i class="delete" @click="deleteClick(index)"></i>
						<img :src="item" :data-preview-src="item" data-preview-group="1">
					</div>
					<div class="button" @click="addImgClick"></div>
				</div>
			</div>
			<!--底部按钮-->
			<div class="bottom-wapper" v-if="bottomWapper">
				<div class="bottom-submit" id="submit">提交</div>
			</div>
		</div>
		<script src="../js/mui.min.js"></script>
		<script src="../js/vue.js"></script>
		<script src="../js/mui.picker.js"></script>
		<script src="../js/mui.poppicker.js"></script>
		<script src="../js/mui.zoom.js"></script>
		<script src="../js/mui.previewimage.js"></script>
		<script type="text/javascript">
			mui.init({
				gestureConfig: {
					tap: true, //默认为true
					doubletap: true, //默认为false
					longtap: true, //默认为false
					swipe: true, //默认为true
					drag: true, //默认为true
					hold: false, //默认为false，不监听
					release: true //默认为false，不监听
				}
			})

			var r = null
			var t = null
			var ri = null
			var image={
			    /* 将图片（路径）转换为Base64 */
			    getBase64FromImageURL(url, callback) {
			        var canvas = document.createElement('canvas'),
			            ctx = canvas.getContext('2d'),
			            img = new Image;
			        img.crossOrigin = 'Anonymous';
			        img.onload = function() {
			            canvas.height = img.height;
			            canvas.width = img.width;
			            ctx.drawImage(img, 0, 0);
			            var base64URL = canvas.toDataURL('image/png');
			            callback(base64URL);
			            canvas = null;
			        };
			        img.src = url;
			    },
			    /* 将base64转换为file类型 */
			    getFileFromBase64(base64URL, filename) {
					const newFileName = filename + new Date().getTime() + Math.floor(Math.random() * 150) + '.png'
			        var arr = base64URL.split(','),
			            mime = arr[0].match(/:(.*?);/)[1],
			            bstr = atob(arr[1]),
			            n = bstr.length,
			            u8arr = new Uint8Array(n);
			        while (n--) {
			            u8arr[n] = bstr.charCodeAt(n);
			        }
			        return new File([u8arr], newFileName, { type: mime });
			    }
			}
			

			var formData = new FormData();
			mui.plusReady(function() {
				r = plus.audio.getRecorder();
			})
			var filelist = new Array();
			var filelist2 = [];
			var matter = new Vue({
				el: "#matter",
				data: {
					sate: false,
					bottomWapper: true,
					recordList: [],
					listImg: []
				},
				methods: {
					// 上传 formdata数据 
					postData:function(myFormData,callback){
						var xhr = new XMLHttpRequest();  
						xhr.open('POST', 'http://192.168.0.102:9527/api_1_0/repairInfo/submit_info', true);  
						xhr.onreadystatechange = function(){  
						    if(xhr.readyState == 4 && xhr.status == 200){  
								// console.log(xhr.responseText,'返回数据');
						        var res = JSON.parse(xhr.responseText) 
								callback && callback(res);
						    }  
						}  
						// console.log(myFormData.get('userID'));
						// console.log(myFormData.get('repairType'));
						// console.log(myFormData.get('repairPlace'));
						// console.log(myFormData.get('repairDetail'));
						// console.log(myFormData.get('contactName'));
						// console.log(myFormData.get('contactPhone'));
						console.log(myFormData.get('repairInfoImg'));
						xhr.send(myFormData);
					},
					addressClick: function() {
						var picker = new mui.PopPicker({
							layer: 3,
							button: ['取消', '确定']
						});

						picker.setData([{
							value: '0',
							text: '宿舍楼1栋',
							children: [{
								value: "1",
								text: "1",
								children: [{
									value: "2",
									text: "1-101"
								}, {
									value: "3",
									text: "1-102"
								}, {
									value: "4",
									text: "1-103"
								}],
							}, {
								value: "5",
								text: "2",
								children: [{
									value: "6",
									text: "2-201"
								}, {
									value: "7",
									text: "2-202"
								}, {
									value: "8",
									text: "2-203"
								}],
							}],

						}, {
							value: '9',
							text: '宿舍楼2栋',
							children: [{
								value: "10",
								text: "1",
								children: [{
									value: "11",
									text: "1-101"
								}, {
									value: "12",
									text: "1-102"
								}, {
									value: "13",
									text: "1-103"
								}],
							}, {
								value: "14",
								text: "2",
								children: [{
									value: "15",
									text: "2-201"
								}, {
									value: "16",
									text: "2-202"
								}, {
									value: "17",
									text: "2-203"
								}],

							}, {
								value: "18",
								text: "3",
								children: [{
									value: "19",
									text: "3-301"
								}, {
									value: "20",
									text: "3-302"
								}, {
									value: "21",
									text: "3-303"
								}]
							}]
						}, ]);
						// 默认第一层显示第1项;第二层显示第2项;第三层显示第3项;
						picker.pickers[0].setSelectedIndex(0);
						picker.pickers[1].setSelectedIndex(1);
						picker.pickers[2].setSelectedIndex(2);
						picker.show(function(selectItems) {
							var text1 = selectItems[0].text;
							var text2 = selectItems[1].text;
							var text3 = selectItems[2].text;
							var text = text1 + '-' + text2 + '-' + text3;
							document.getElementById('addresstxt').innerText = text;
						})


					},
					classifyClick: function() {
						var picker = new mui.PopPicker({
							layer: 1,
							buttons: ['取消', '确定']
						});
						picker.setData([{
							value: "first",
							text: "照明故障"
						}, {
							value: "second",
							text: "电器故障"
						}, {
							value: "third",
							text: "设备故障"
						}, {
							value: "fourth",
							text: "供水故障"
						}]);
						// 默认显示第4项
						picker.pickers[0].setSelectedIndex(3, 2000);
						picker.show(function(selectItems) {
							var text = selectItems[0].text;
							document.getElementById('type').innerText = text;
						});

					},
					addImgClick: function() {
						var that = this
						// 从相册中选择图片
						mui.toast('最多选择5张');
						plus.gallery.pick(function(e) {
							var lfs = e.files;
							that.listImg = e.files;
							for (let i = 0, len = e.files.length; i < len; ++i) {
								url = e.files[i]; // 图片
								// console.log(url);
								filelist.push(e.files[i]); //待上传图片数组
							}
						}, function(e) {
							mui.toast('取消选择图片');
						}, {
							filter: 'image',
							multiple: true,
							maximum: 5,
							system: false,
							onmaxed: function() {
								plus.nativeUI.alert('最多只能选择5张图片');
							}
						});
					},

					deleteClick: function(num) {
						console.log(num)
						this.listImg.splice(num, 1)
					}
				}
			})
			document.getElementById("submit").onclick = function() {
				var Sdata = plus.webview.currentWebview();
				userID = Sdata.userID;
				formData.append('userID', userID);
				repairPlace = document.getElementById("addresstxt").innerText;
				formData.append('repairPlace', repairPlace);
				repairType = document.getElementById("type").innerText;
				formData.append('repairType', repairType);
				repairDetail = document.getElementById("textarea").value;
				formData.append('repairDetail', repairDetail);
				contactName = document.getElementById("contactName").value;
				formData.append('contactName', contactName);
				contactPhone = document.getElementById("contactPhone").value;
				formData.append('contactPhone', contactPhone);
				if (repairPlace != '' && repairType != '' && repairDetail != '' && contactName != '' && contactPhone != '' &&filelist != []) {
				
						// 通过校验
						let pList = [];
						for (let i = 0; i < filelist.length; i++) {
							let p =  new Promise((resolve,reject)=>{
								image.getBase64FromImageURL(filelist[i], (base64URL)=> {
								    // console.log(base64URL);
								    var imgURL = image.getFileFromBase64(base64URL, '');
								    // console.log(imgURL,'看一下文件类型');
									
									filelist2.push(imgURL);
									resolve();
								});
							})
							pList.push(p)
						}
						Promise.all(pList).then(res=>{
								for (let i = 0; i < filelist2.length; i++) {
								formData.append('repairInfoImg',filelist2[i]);//添加图片
									}
							    
								matter.postData(formData,res=>{
									// 提交完数据
									if (res.code == 2000) {
										mui.toast("提交成功");
										
										location.reload();
									} else {
										mui.toast(res.data.error);
										location.reload();
									}
								});
							return
						})
						mui.post('http://192.168.0.102:9527/api_1_0/repairInfo/submit_info',{
														formData
													},function(data){
														if(data.code == 2000)
														{
															mui.toast("提交成功");
															mui.openWindow({
																url:'index.html',
																id:'index.html',
																styles:{
																	top:"0px",
																	buttom:"0px"
																}
																
																
															})
														}
														else
														{
															mui.toast(data.data.error);
															location.reload();
														}
													},'json'
												);
				}else{
					alert("请完整填写保修表！")
				}
				return;
			};

			mui.previewImage();
		</script>
	</body>

</html>
